<template>
  <div class="stock-screen">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>股票筛选</span>
        </div>
      </template>
      
      <el-form :model="filterForm" inline>
        <el-form-item label="行业">
          <el-input v-model="filterForm.industry" placeholder="请输入行业"></el-input>
        </el-form-item>
        <el-form-item label="市值范围">
          <el-input-number 
            v-model="filterForm.market_value_min" 
            :min="0" 
            placeholder="最小值">
          </el-input-number>
          <span class="separator">-</span>
          <el-input-number 
            v-model="filterForm.market_value_max" 
            :min="0" 
            placeholder="最大值">
          </el-input-number>
        </el-form-item>
        <el-form-item label="换手率">
          <el-input-number 
            v-model="filterForm.turnover_rate_min" 
            :min="0" 
            :max="100"
            placeholder="最小换手率">
          </el-input-number>
        </el-form-item>
        <el-form-item label="市盈率">
          <el-input-number 
            v-model="filterForm.pe_min" 
            :min="0" 
            placeholder="最小值">
          </el-input-number>
          <span class="separator">-</span>
          <el-input-number 
            v-model="filterForm.pe_max" 
            :min="0" 
            placeholder="最大值">
          </el-input-number>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :loading="loading">
            搜索
          </el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table :data="stockList" v-loading="loading">
        <el-table-column prop="code" label="股票代码" width="120" />
        <el-table-column prop="name" label="股票名称" width="120" />
        <el-table-column prop="industry" label="行业" />
        <el-table-column prop="market_value" label="市值(亿元)" />
        <el-table-column prop="turnover_rate" label="换手率(%)" />
        <el-table-column prop="pe_ratio" label="市盈率" />
        <el-table-column fixed="right" label="操作" width="120">
          <template #default="{ row }">
            <el-button 
              :type="row.is_following ? 'danger' : 'success'" 
              @click="handleFollow(row)"
              :loading="followLoading"
            >
              {{ row.is_following ? '取消关注' : '关注' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import request from '../utils/request'

const loading = ref(false)
const followLoading = ref(false)
const stockList = ref([])

const filterForm = reactive({
  industry: '',
  market_value_min: null,
  market_value_max: null,
  turnover_rate_min: null,
  pe_min: null,
  pe_max: null
})

const handleSearch = async () => {
  loading.value = true
  try {
    // 过滤掉空值
    const requestData = Object.fromEntries(
      Object.entries(filterForm).filter(([_, value]) => value !== null && value !== '')
    )
    const { results } = await request.post('/stocks/screen/', requestData)
    // 获取用户所有关注股票
    const followedResponse = await request.get('/stocks/my_stocks/')
    const followedCodes = new Set(followedResponse.map(s => s.symbol))
    
    // 添加is_following字段
    stockList.value = results.map(stock => {
      const code = stock.code.split('.')[0];
      return {
        ...stock,
        is_following: followedCodes.has(code)
      }
    })
    // console.log('更新后的 stockList:', stockList.value); // 添加调试信息
  } catch (error) {
    // 错误已经被拦截器处理
  } finally {
    loading.value = false
  }
}

const handleFollow = async (stock) => {
  followLoading.value = true;
  console.log(stock);
  try {
    // 提取代码部分
    const code = stock.code.split('.')[0];
    // 使用K线页面的逻辑
    if (stock.is_following) {
      // 修改为 POST 请求
      const response = await request.post(`/stocks/${code}/unfollow/`); 
      ElMessage.success(response.detail || '取消关注成功');
      stock.is_following = false;
    } else {
      const response = await request.post(`/stocks/${code}/follow/`);
      ElMessage.success(response.detail || '关注成功');
      stock.is_following = true;
    }
  } catch (error) {
    // 错误已经被拦截器处理
  } finally {
    followLoading.value = false;
  }
}

const resetForm = () => {
  Object.keys(filterForm).forEach(key => {
    filterForm[key] = key === 'industry' ? '' : null
  })
}
</script>

<style scoped>
.stock-screen {
  padding: 20px;
}

.separator {
  margin: 0 10px;
}
</style> 